//
//  ConversationListViewController.m
//  TIMChat
//
//  Created by wilderliao on 16/2/16.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ConversationListViewController.h"

#import "ConversationListTableViewCell.h"

#import "privateChat.h"
#import "MessageTableViewCell.h"
#import "SystemMessageViewController.h"
#import "PerMessageViewController.h"

@interface ConversationListViewController ()
{
    
}
@property (nonatomic, strong) NSMutableArray *chatListArr; // 列表数组
@property (nonatomic, strong) NSMutableDictionary *userDict; // 用户字典
@property (nonatomic, strong) NSArray *arr;
@property (nonatomic, strong) NSString *num0;
@property (nonatomic, strong) NSString *num1;
@end

@implementation ConversationListViewController

// 懒加载
- (NSMutableArray *)chatListArr {
    if (_chatListArr == nil) {
        _chatListArr = [[NSMutableArray alloc] init];
    }
    return _chatListArr;
}
- (NSMutableDictionary *)userDict {
    if (_userDict == nil) {
        _userDict = [[NSMutableDictionary alloc] init];
    }
    return _userDict;
}

- (void)viewWillLayoutSubviews {
    
    if (self.isLive) {
        self.view.frame = CGRectMake(0, SCREEN_HEIGHT/2, SCREEN_WIDTH, SCREEN_HEIGHT/2);
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NetworkTool sharedTool] requestWithName:@"未读消息" URLString:APIUnreadTips parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        self.num0 = responseObject[@"data"][@"notification"];
        self.num1 = responseObject[@"data"][@"message"];
        
        [self.tableView reloadData];
        
    }];
    [self chatListConversations];
    
    if (self.isLive) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
    
}


- (void)c2cNotification:(NSNotification *)notification {
    NSLog(@"--接收到私聊提醒通知--\n%@", notification.userInfo);
    //    [self updateNum];
    [self chatListConversations];
}


- (void)msgchatVC:(NSNotification *)notification {
    NSDictionary *privateChat = notification.userInfo;
    NSLog(@"--接收到私聊的消息通知--\n%@", privateChat);
    
    NSString *str = privateChat[@"receiveInfo"]; // 把聊天对象信息赋值
    
    NSError *err;
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
    
    
    TIMConversation *conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:infoDict[@"imId"]];
    
    [conversation setReadMessage];
    
    //    NSMutableArray *chatArr = self.chatListArr[tag];
    //
    //    NSDictionary *dict = chatArr[1];
    IMAUser *user = [[IMAUser alloc] init];
    user.nickName = infoDict[@"nickname"];
    user.userId = infoDict[@"uid"];
    user.remark = infoDict[@"nickname"];
    user.icon = infoDict[@"headpic"];
    
    ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
    
    chatVC.isLive = self.isLive;
    
    [self.navigationController pushViewController:chatVC animated:YES];
    
    
}

#pragma mark ===========私聊列表=========
- (void)chatListConversations {
    NSMutableArray *userArr = [[NSMutableArray alloc] init];
    for (NSInteger i = 0;i < _conversationList.count;i++) {
        id<IMAConversationShowAble> currentConv = [_conversationList objectAtIndex:i];
        // 添加用户id
        [userArr addObject:[currentConv showTitle]];
    }
    //        NSLog(@"userArr = %@", userArr);
    
    NSString *userIdStr = [userArr componentsJoinedByString:@","];
    // 批量查询用户信息
    NSDictionary *param = @{@"ids":userIdStr,
                            @"per_page":@"10000"};
    [[NetworkTool sharedTool] requestWithName:@"批量查询用户信息" URLString:APIUserInfos parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = [[NSArray alloc] init];
        arr = responseObject[@"data"];
        
        for (int i = 0; i < arr.count; i++) {
            NSDictionary *user = [[NSDictionary alloc] init];
            user = arr[i];
            [_userDict setValue:user forKey:user[@"user_id"]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    }];
    
//    [privateChat chatListConversationBlock:^(NSMutableArray *conversationArr, NSMutableArray *chatListArr) {
//
//        NSMutableArray *userArr = [[NSMutableArray alloc] init];
//        for (NSArray *arr in chatListArr) {// 信息 userId 未读数量
//            NSString *uid = arr[1];
//            [userArr addObject:uid];
//        }
//
//        //        NSLog(@"userArr = %@", userArr);
//
//        NSString *userIdStr = [userArr componentsJoinedByString:@","];
//        // 批量查询用户信息
//        NSDictionary *param = @{@"ids":userIdStr,
//                                @"per_page":@"10000"};
//        [[NetworkTool sharedTool] requestWithName:@"批量查询用户信息" URLString:APIUserInfos parameters:param method:@"GET" callBack:^(id responseObject) {
//
//            NSArray *arr = [[NSArray alloc] init];
//            arr = responseObject[@"data"];
//
//            NSMutableDictionary *userDict = [[NSMutableDictionary alloc] init];
//
//            for (int i = 0; i < arr.count; i++) {
//                NSDictionary *user = [[NSDictionary alloc] init];
//                user = arr[i];
//                [userDict setValue:user forKey:user[@"user_id"]];
//            }
//
//            //            NSLog(@"1111 %@", chatListArr);
//            for (NSMutableArray *ma in chatListArr) {
//                NSString *uid = ma[1];
//                [ma removeObjectAtIndex:1];
//                [ma insertObject:userDict[uid] atIndex:1];
//            }
//            //            NSLog(@"user %@", chatListArr);
//
//
//            [self.chatListArr removeAllObjects];
//            [self.chatListArr setArray:chatListArr];
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.tableView reloadData];
//            });
//
//        }];
//    }];
}

- (void)dealloc
{
    [self.KVOController unobserveAll];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cNotification" object:nil];
}

- (void)addHeaderView
{
    
}
- (void)addFooterView
{
    
}

- (BOOL)hasData
{
    BOOL has = _conversationList.count != 0;
    return has;
}

- (void)addRefreshScrollView
{
    _tableView = [[SwipeDeleteTableView alloc] init];
    _tableView.frame = self.view.bounds;
    
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = kClearColor;
    _tableView.scrollsToTop = YES;
    [self.view addSubview:_tableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [_tableView setTableFooterView:v];
    
    _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.refreshScrollView = _tableView;
    
//    if (self.isLive) {
//
//        //        UIView *headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
//        //        [self.view addSubview:headBgView];
//        //        headBgView.backgroundColor = kWhiteColor;
//
//        UILabel *chatHead = [[UILabel alloc] init];
//        [self.view addSubview:chatHead];
//        chatHead.font = kUHSystemFontWithSize(14);
//        chatHead.textColor = kBlackColor;
//        chatHead.backgroundColor = kWhiteColor;
//        chatHead.layer.borderColor = UISeparatedColorRGB.CGColor;
//        chatHead.text = [NSString stringWithFormat:@"私信"];
//        chatHead.textAlignment = NSTextAlignmentCenter;
//        chatHead.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
//
//        UIButton *closeChat = [UIButton buttonWithType:UIButtonTypeCustom];
//        [self.view addSubview:closeChat];
//        [closeChat setImage:[UIImage imageNamed:@"live_zhubo_close"] forState:UIControlStateNormal];
//        closeChat.frame = CGRectMake(SCREEN_WIDTH-40, 0, 40, 40);
//        [closeChat addTarget:self action:@selector(maskClick) forControlEvents:UIControlEventTouchUpInside];
//
//        self.tableView.frame = CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT/2-40);
//    }
    
}

- (void)maskClick {
    self.navigationController.view.hidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"消息";
    [self pinHeaderView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(c2cNotification:)name:@"c2cNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgchatVC:)name:@"msgchatVC" object:nil];
    self.arr = @[@"系统消息", @"私聊"];
    if (self.isLive) {
        self.arr = @[@"私聊"];
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    [self chatListConversations];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[IMAPlatform sharedInstance].conversationMgr releaseChattingConversation];
}

- (void)addSearchController
{
}

- (void)configOwnViews
{
    IMAConversationManager *mgr = [IMAPlatform sharedInstance].conversationMgr;
    _conversationList = [mgr conversationList];
    
    
    __weak ConversationListViewController *ws = self;
    mgr.conversationChangedCompletion = ^(IMAConversationChangedNotifyItem *item) {
        if (item.type == EIMAConversation_DisConnected) {
            return;
        }
        if ([item.conversation type] == TIM_GROUP) {
            [self chatListConversations];
            return;
        }
        [ws onConversationChanged:item];
        
        [self chatListConversations];
    };
    
//        [[IMAPlatform sharedInstance].conversationMgr addConversationChangedObserver:self handler:@selector(onConversationChanged:) forEvent:EIMAConversation_AllEvents];
    
    
    
    self.KVOController = [FBKVOController controllerWithObserver:self];
    [self.KVOController observe:[IMAPlatform sharedInstance].conversationMgr keyPath:@"unReadMessageCount" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [ws onUnReadMessag];
    }];
    [ws onUnReadMessag];
}

- (void)onUnReadMessag
{
    NSInteger unRead = [IMAPlatform sharedInstance].conversationMgr.unReadMessageCount;
    
    NSString *badge = nil;
    if (unRead > 0 && unRead <= 99)
    {
        badge = [NSString stringWithFormat:@"%d", (int)unRead];
    }
    else if (unRead > 99)
    {
        badge = @"99+";
    }
    
//    self.navigationController.tabBarItem.badgeValue = badge;
}


- (void)onConversationChanged:(IMAConversationChangedNotifyItem *)item
{
    // sss
	//由于这个vc还分是不是从直播间打开的，所以section的话要通过是否直播来区分0还是1;
	int sectionNum = 1-self.isLive;
    switch (item.type)
    {
        case EIMAConversation_SyncLocalConversation:
        {
            [self reloadData];
        }
            
            break;
        case EIMAConversation_BecomeActiveTop:
        {
            [self.tableView beginUpdates];
            [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:item.index inSection:sectionNum] toIndexPath:[NSIndexPath indexPathForRow:item.toIndex inSection:sectionNum]];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_NewConversation:
        {
            if ((!item.conversation.msgList && !item.conversation.lastMessage && !item.conversation.receiveMsg) || [item.conversation.receiver isEqualToString:@"-10000"]) {
                return;
            }
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:sectionNum];
            [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_DeleteConversation:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:sectionNum];
            [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_Connected:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:sectionNum];
            [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_DisConnected:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:sectionNum];
            [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_ConversationChanged:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:sectionNum];
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            
            [self.tableView endUpdates];
        }
            break;
        default:
            
            break;
    }
    
}
- (void)onRefresh
{
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        [self reloadData];
    //    });
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.isLive && indexPath.section == 0) {
        return SW(9)+20;
    }
    id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
    return [conv showHeight];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isLive) {
        for (NSInteger i = 0;i < _conversationList.count;i++) {
            id<IMAConversationShowAble> currentConv = [_conversationList objectAtIndex:i];
            // 删除群聊会话
            if ([currentConv conversationType] == TIM_GROUP) {
                [_conversationList removeObject:currentConv];
            }
        }
        return [_conversationList count];
    }
	else {
		if(section == 0) {
			return 2;
		}
		else{
			return [_conversationList count];
		}
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isLive) {
        id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
        NSString *reuseidentifier = [conv showReuseIndentifier];
        [conv attributedDraft];
        id<IMAConversationShowAble> tempCon = [[[IMAPlatform sharedInstance].conversationMgr conversationList] objectAtIndex:indexPath.row];
        [tempCon attributedDraft];
        
        ConversationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseidentifier];
        if (!cell)
        {
            cell = [[[conv showCellClass] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseidentifier];
        }
        
        if (self.userDict.count > indexPath.row) {
            NSString *userId = [conv showTitle];
            NSDictionary *dict = _userDict[userId];
            if (dict) {
                cell.nickname =  dict[@"nickname"];
                cell.userFace =  dict[@"face"];
            }
        }
        
        [cell configCellWith:conv];
        
        //cell.contentView.tag = indexPath.row;
        //[cell.contentView addTarget:self action:@selector(tableViewCellClick:)];
        
        return cell;
    }
	else {
		if (indexPath.section == 0) {
			
			MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
			cell.sign.hidden = YES;
			cell.date.hidden = YES;
			cell.num.hidden = YES;
			cell.num.x = SCREEN_WIDTH-SW(20)-30;
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			cell.nickName.centerY = cell.headPic.centerY;
			NSLog(@"---num-%@, %@", self.num0, self.num1);
			if (indexPath.row == 0) {
				cell.headPic.image = IMAGE(@"icon_info_system");
				cell.nickName.text = @"系统消息";
				if (![self.num0 isEqualToString:@"0"]) {
					cell.num.text = self.num0;
					cell.num.hidden = NO;
				}
			}
			else {
				cell.headPic.image = IMAGE(@"icon_info_question");
				cell.nickName.text = @"站内信";
				if (![self.num1 isEqualToString:@"0"]) {
					cell.num.text = self.num1;
					cell.num.hidden = NO;
				}
			}
			return cell;
		}
		else {
			id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
			NSString *reuseidentifier = [conv showReuseIndentifier];
			[conv attributedDraft];
			id<IMAConversationShowAble> tempCon = [[[IMAPlatform sharedInstance].conversationMgr conversationList] objectAtIndex:indexPath.row];
			[tempCon attributedDraft];
			
			ConversationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseidentifier];
			if (!cell)
			{
				cell = [[[conv showCellClass] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseidentifier];
			}
			
			if (self.userDict.count > indexPath.row) {
				NSString *userId = [conv showTitle];
				NSDictionary *dict = _userDict[userId];
				cell.nickname =  dict[@"nickname"];
				cell.userFace =  dict[@"face"];
			}
			
			//        if (self.chatListArr.count > indexPath.row) {
			//            NSArray *chatArr = self.chatListArr[indexPath.row];
			//            NSDictionary *dict = chatArr[1];
			//            cell.nickname =  dict[@"nickname"];
			//            cell.userFace =  dict[@"face"];
			//            NSString *userId = dict[@"user_id"];
			//            for (NSInteger i = 0;i < _conversationList.count;i++) {
			//                id<IMAConversationShowAble> currentConv = [_conversationList objectAtIndex:i];
			//                if ([[currentConv showTitle] isEqualToString:userId]) {
			//                    conv = currentConv;
			//                    break;
			//                }
			//            }
			//        }
			[cell configCellWith:conv];
			return cell;
		}
	}
}

//   tableView代理方法 设置分区高度（可以根据不同分区设置不同高度等实现自定义）
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.isLive) {
        return 40;
    }
    return 10;
}
//  自定义分区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (self.isLive) {
        
        //        UIView *headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        //        [self.view addSubview:headBgView];
        //        headBgView.backgroundColor = kWhiteColor;
        
        UIView *headerView = [[UIView alloc] init];
        UILabel *chatHead = [[UILabel alloc] init];
        [headerView addSubview:chatHead];
        chatHead.font = kUHSystemFontWithSize(14);
        chatHead.textColor = kBlackColor;
        chatHead.backgroundColor = kWhiteColor;
        chatHead.layer.borderColor = UISeparatedColorRGB.CGColor;
        chatHead.text = [NSString stringWithFormat:@"私信"];
        chatHead.textAlignment = NSTextAlignmentCenter;
        chatHead.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
        
        UIButton *closeChat = [UIButton buttonWithType:UIButtonTypeCustom];
        [headerView addSubview:closeChat];
        [closeChat setImage:[UIImage imageNamed:@"live_zhubo_close"] forState:UIControlStateNormal];
        closeChat.frame = CGRectMake(SCREEN_WIDTH-40, 0, 40, 40);
        [closeChat addTarget:self action:@selector(maskClick) forControlEvents:UIControlEventTouchUpInside];
        if (self.tableView.bounds.origin.y != 0) {
            CGRect bounds = self.tableView.bounds;
            bounds.origin.y = 0;
            self.tableView.bounds = bounds;
            [self.tableView layoutIfNeeded];
        }
        
        return headerView;
    }
    
    
    static NSString * identy = @"head";
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    if (!hf) {
        NSLog(@"%ld",(long)section);
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        //        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 30)];
        //        [hf addSubview:title];
        //        title.text = self.arr[section];
        
        //        title.font = kUHSystemFontWithSize(15);
    }
    return hf;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMAConversation *conv = [_conversationList objectAtIndex:indexPath.row];
    [[IMAPlatform sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
	
	if (self.isLive) {
		id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
		NSString *userId = [conv showTitle];
		NSDictionary *dict = _userDict[userId];
		
		//        NSMutableArray *chatArr = self.chatListArr[indexPath.row];
		//        NSDictionary *dict = chatArr[1];
		
		IMAUser *user = [[IMAUser alloc] init];
		user.nickName = dict[@"nickname"];
		user.userId = dict[@"user_id"];
		user.remark = dict[@"nickname"];
		user.icon = dict[@"face"];
		
#if kTestChatAttachment
		ChatViewController *vc = [[CustomChatUIViewController alloc] initWith:user];
#else
		ChatViewController *vc = [[IMAChatViewController alloc] initWith:user];
#endif
		
		// 隐藏底部的buttomBar 当 push 的时候
		//        [self setHidesBottomBarWhenPushed:YES];
		vc.isLive = YES;
		[self.navigationController pushViewController:vc animated:YES];
	}
	else {
		if (indexPath.section == 0 && indexPath.row == 0) {
			[self.navigationController pushViewController:[[SystemMessageViewController alloc] init] animated:YES];
		}
		
		else if (indexPath.section == 0 && indexPath.row == 1) {
			[self.navigationController pushViewController:[[PerMessageViewController alloc] init] animated:YES];
		}
		else {
			
			id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
			NSString *userId = [conv showTitle];
			NSDictionary *dict = _userDict[userId];
			
			//        NSMutableArray *chatArr = self.chatListArr[indexPath.row];
			//        NSDictionary *dict = chatArr[1];
			
			IMAUser *user = [[IMAUser alloc] init];
			user.nickName = dict[@"nickname"];
			user.userId = dict[@"user_id"];
			user.remark = dict[@"nickname"];
			user.icon = dict[@"face"];
			
#if kTestChatAttachment
			ChatViewController *vc = [[CustomChatUIViewController alloc] initWith:user];
#else
			ChatViewController *vc = [[IMAChatViewController alloc] initWith:user];
#endif
			
			// 隐藏底部的buttomBar 当 push 的时候
			//        [self setHidesBottomBarWhenPushed:YES];
			
			[self.navigationController pushViewController:vc animated:YES];
			
		}
	}
}


- (void)tableViewCellClick:(UITableViewCell *)sender {

    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer
                                             *)sender;
    
    NSInteger tag = [tapRecognizer.view tag];
    
    id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:tag];
    NSString *userId = [conv showTitle];
    NSDictionary *dict = _userDict[userId];
    
    //        NSMutableArray *chatArr = self.chatListArr[indexPath.row];
    //        NSDictionary *dict = chatArr[1];
    
    IMAUser *user = [[IMAUser alloc] init];
    user.nickName = dict[@"nickname"];
    user.userId = dict[@"user_id"];
    user.remark = dict[@"nickname"];
    user.icon = dict[@"face"];
    
#if kTestChatAttachment
    ChatViewController *vc = [[CustomChatUIViewController alloc] initWith:user];
#else
    ChatViewController *vc = [[IMAChatViewController alloc] initWith:user];
#endif
    
    vc.isLive = self.isLive;
    
    // 隐藏底部的buttomBar 当 push 的时候
    //        [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
    //        id<IMAConversationShowAble> convable = [_conversationList objectAtIndex:indexPath.row];
    //        ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //        IMAConversation *conv = (IMAConversation *)convable;
    //        switch ([convable conversationType])
    //        {
    //            case IMA_C2C:
    //            case IMA_Group:
    //            {
    //                IMAUser *user = [[IMAPlatform sharedInstance] getReceiverOf:conv];
    //
    //                if (user)
    //                {
    //                    //                [[AppDelegate sharedAppDelegate] pushToChatViewControllerWith:user];
    //
    //                    [conv setReadAllMsg];
    //
    //                    [cell refreshCell];
    //                }
    //                else
    //                {
    //                    if ([conv type] == TIM_C2C)
    //                    {
    //                        // 与陌生人聊天
    //                        [[IMAPlatform sharedInstance] asyncGetStrangerInfo:[conv receiver] succ:^(IMAUser *auser) {
    //
    //                            //                            [[AppDelegate sharedAppDelegate] pushToChatViewControllerWith:auser];
    //
    //                            [conv setReadAllMsg];
    //                            ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //                            [cell refreshCell];
    //
    //                        } fail:^(int code, NSString *msg) {
    //                            DebugLog(@"Fail:--> code=%d,msg=%@,fun=%s", code, msg,__func__);
    //                            [[HUDHelper sharedInstance] tipMessage:IMALocalizedError(code, msg)];
    //                            [[IMAPlatform sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
    //                        }];
    //                    }
    //                    else if ([conv type] == TIM_GROUP)
    //                    {
    //                        // 有可能是因为退群本地信息信息未同步
    //                        [[IMAPlatform sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
    //                    }
    //
    //                }
    //            }
    //                break;
    //
    //            case IMA_Sys_NewFriend:
    //            {
    //                [conv setReadAllMsg];
    //                [cell refreshCell];
    //                [IMAPlatform sharedInstance].contactMgr.hasNewDependency = NO;
    //
    //                FutureFriendsViewController *vc = [[FutureFriendsViewController alloc] init:YES];
    //                //            [[AppDelegate sharedAppDelegate] pushViewController:vc];
    //            }
    //                break;
    //
    //            case IMA_Sys_GroupTip:
    //            {
    //                [conv setReadAllMsg];
    //                [cell refreshCell];
    //                [IMAPlatform sharedInstance].contactMgr.hasNewDependency = NO;
    //                GroupSystemMsgViewController *vc = [[GroupSystemMsgViewController alloc] init];
    //                //            [[AppDelegate sharedAppDelegate] pushViewController:vc];
    //            }
    //                break;
    //
    //            case IMA_Connect:
    //            default:
    //                break;
    //        }
    
}


@end
